//
//  ZhifuPass3ViewController.m
//  specialine
//
//  Created by 往返网络 on 17/7/19.
//  Copyright © 2017年 com. All rights reserved.
//

#import "ZhifuPass3ViewController.h" //支付密码重置2
#import "PublicMethod.h"

#define return_tag 2000
#define complete_tag 2001
#define kDotSize CGSizeMake (10, 10) //密码点的大小
#define kDotCount 6  //密码个数
#define K_Field_Height 80.0/H_BASE*SCREEN_H  //每一个输入框的高度
//定义登录URL
#define URL_ZHIFU [NSString stringWithFormat:@"%@/Appcustomernewer/Pay/paySetPwConfig?type=get",BASE_URL]
@interface ZhifuPass3ViewController ()<UITextFieldDelegate>
@property (nonatomic,strong)AFHTTPSessionManager* manger;

@end
@implementation ZhifuPass3ViewController
{
    UITextField * textFieldmima;
    NSMutableArray * dotArray; //用于放密码黑点的数组
    UIButton * nextbtn; //下一步
}

- (void)viewWillAppear:(BOOL)animated{
    
    self.navigationController.navigationBar.hidden = YES;
    self.tabBarController.tabBar.hidden = YES;
    
}
- (void)viewWillDisappear:(BOOL)animated{
    
    self.navigationController.navigationBar.hidden = NO;
    self.tabBarController.tabBar.hidden = NO;
}

- (void)viewDidLoad {
    
    [super viewDidLoad];
    [self createUI];
    // Do any additional setup after loading the view.
}

- (void)createUI{
    
    self.view.backgroundColor = COLORRGBA(239, 239, 239, 1);
    
    UIView * titleview = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_W, 128.0/1334*SCREEN_H)];
    
    titleview.backgroundColor = COLORRGBA(7, 24, 57, 1);
    
    [self.view addSubview:titleview];
    
    float fontsize = 18;
    
    float corensize = 17;
    
    fontsize = SCREEN_H < 667 ? 16 : 20 ;
    
    corensize = SCREEN_H < 667 ? 15 : 19 ;
    
    if (SCREEN_H == 667) {
        fontsize = 18;
        corensize = 17;
    }
    
    UIButton * leftlable  = [[UIButton alloc]initWithFrame:CGRectMake(0, 20+14.0/1334*SCREEN_H, 80.0/W_BASE*SCREEN_W, 60.0/1334.0*SCREEN_H)];
    
    [leftlable setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    
    leftlable.titleLabel.font = [UIFont fontWithName:@"iconfont" size:fontsize+3];
    
    [leftlable setTitle:@"\U0000e697" forState:UIControlStateNormal];
    
    [leftlable.titleLabel setTextAlignment:NSTextAlignmentCenter];
    
    [leftlable addTarget:self action:@selector(enterClick:) forControlEvents:UIControlEventTouchUpInside];
    leftlable.tag = return_tag;
    [titleview addSubview:leftlable];
    
    UILabel * titlelab = [[UILabel alloc]initWithFrame:CGRectMake(0, CGRectGetMinY(leftlable.frame), SCREEN_W, CGRectGetHeight(leftlable.frame))];
    
    titlelab.textAlignment = NSTextAlignmentCenter;
    
    titlelab.textColor = [UIColor whiteColor];
    
    titlelab.font = [UIFont systemFontOfSize:fontsize - 1];
    
    titlelab.text = @"重置支付密码";
    
    [titleview addSubview:titlelab];
    
    UILabel * phonelabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 128.0/H_BASE*SCREEN_H, SCREEN_W, 80.0/H_BASE*SCREEN_H)];
    [self.view addSubview:phonelabel];
    phonelabel.textColor = [UIColor blackColor];
    phonelabel.font = [UIFont boldSystemFontOfSize:fontsize-4];
    phonelabel.textAlignment = NSTextAlignmentCenter;
    phonelabel.text = @"请再次输入";
    textFieldmima = [[UITextField alloc] initWithFrame:CGRectMake(30.0/W_BASE*SCREEN_W, CGRectGetMaxY(phonelabel.frame), SCREEN_W - 60.0/W_BASE*SCREEN_W, K_Field_Height)];
    textFieldmima.backgroundColor = [UIColor whiteColor];
    //输入的文字颜色为白色
    textFieldmima.textColor = [UIColor whiteColor];
    //输入框光标的颜色为白色
    textFieldmima.tintColor = [UIColor whiteColor];
    textFieldmima.delegate = self;
    textFieldmima.autocapitalizationType = UITextAutocapitalizationTypeNone;
    textFieldmima.keyboardType = UIKeyboardTypeNumberPad;
    textFieldmima.layer.borderColor = [COLORRGBA(204, 204, 204, 1)CGColor];
    textFieldmima.layer.borderWidth = 1;
    [textFieldmima addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    [self.view addSubview:textFieldmima];
    [textFieldmima becomeFirstResponder];
    [self initPwdTextField];//创建密码tf的分割线
    
    nextbtn = [[UIButton alloc]initWithFrame:CGRectMake(25.0/W_BASE*SCREEN_W, CGRectGetMaxY(textFieldmima.frame)+68.0/H_BASE*SCREEN_H,SCREEN_W- 50.0/W_BASE*SCREEN_W, 80.0/H_BASE*SCREEN_H)];
    nextbtn.backgroundColor = COLORRGBA(59, 214, 117, 0.5);
    [nextbtn setTitle:@"完成" forState:UIControlStateNormal];
    nextbtn.layer.cornerRadius = 2;
    nextbtn.titleLabel.font = [UIFont systemFontOfSize:fontsize];
    [self.view addSubview:nextbtn];
    nextbtn.tag = complete_tag;
    [nextbtn addTarget:self action:@selector(enterClick:) forControlEvents:UIControlEventTouchUpInside];
    nextbtn.userInteractionEnabled = NO;
    
    
    
}
#pragma mark  - - -- - - - - - 将输入密码的tf分割成点 － － － － － － － － － － －
- (void)initPwdTextField
{
    //每个密码输入框的宽度
    CGFloat width = (SCREEN_W - 32) / kDotCount;
    //生成分割线
    for (int i = 0; i < kDotCount - 1; i++) {
        UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(CGRectGetMinX(textFieldmima.frame) + (i + 1) * width, CGRectGetMinY(textFieldmima.frame), 1, K_Field_Height)];
        lineView.backgroundColor = COLORRGBA(204, 204, 204, 1);
        [self.view addSubview:lineView];
    }
    
    dotArray = [[NSMutableArray alloc] init];
    //生成中间的点
    for (int i = 0; i < kDotCount; i++) {
        UIView *dotView = [[UIView alloc] initWithFrame:CGRectMake(CGRectGetMinX(textFieldmima.frame) + (width - kDotCount) / 2 + i * width, CGRectGetMinY(textFieldmima.frame) + (K_Field_Height - kDotSize.height) / 2, kDotSize.width, kDotSize.height)];
        dotView.backgroundColor = [UIColor blackColor];
        dotView.layer.cornerRadius = kDotSize.width / 2.0f;
        dotView.clipsToBounds = YES;
        dotView.hidden = YES; //先隐藏
        [self.view addSubview:dotView];
        //把创建的黑色点加入到数组中
        [dotArray addObject:dotView];
    }
}

#pragma mark - - - - - - - - - - -  Action - - - - - - - - - - - - -
- (void)enterClick:(UIButton *)btn{
    
    switch (btn.tag) {
        case return_tag:
            //返回
            [self.navigationController popViewControllerAnimated:YES];
            break;
        case complete_tag:
            //完成
        {
            //请求接口。。
//            ALERT(@"提示", @"重置密码成功", self, @"确定", nil);
            [self.view endEditing:YES];
            //核对2次密码是否一致
            if (![self.lastps isEqualToString:textFieldmima.text]) {
                ALERT(@"提示", @"2次密码输入不一致", self, @"确定", nil);
                return;
            }
            //请求数据
            [self configZhifu];
            break;
        }
        default:
            break;
    }
}

- (void)configZhifu{

    //开始动画
    UIImageView * im = [PublicMethod startAnimation];
    
    NSUserDefaults * user = [NSUserDefaults standardUserDefaults];
    
    NSString * token = [user objectForKey:USER_TOCKE];
    
    NSString * url = [NSString stringWithFormat:@"%@&token=%@&code=%@&password=%@",URL_ZHIFU,token,self.code,textFieldmima.text];
    NSLog(@"支付密码确认 url %@",url);

    [self.manger GET:url parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        
        if (responseObject) {
            
            NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            
            NSInteger code = [dict[@"code"]integerValue];
            
            if (code == 0) {
                
                //获取验证码成功
                [im stopAnimating];
                ALERT(@"提示", dict[@"info"], self, @"确定", nil);
                //回到主页面
                NSArray * viewarr = self.navigationController.viewControllers;
                UIViewController * vc = (UIViewController*)viewarr[1];
                [self.navigationController popToViewController:vc animated:YES];
                
            }else{
                
                [im stopAnimating];
                ALERT(@"提示", dict[@"info"], self, @"确定", nil);
                
            }
            
            
        }
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
        [im stopAnimating];
        
        ALERT(@"提示", @"网络请求失败", self, @"确定", nil);
        
    }];
    




}
/**
 *  重置显示的点
 */
- (void)textFieldDidChange:(UITextField *)textField
{
    NSLog(@"%@", textField.text);
    if (textField == textFieldmima) {
        for (UIView *dotView in dotArray) {
            dotView.hidden = YES;
        }
        for (int i = 0; i < textField.text.length; i++) {
            ((UIView *)[dotArray objectAtIndex:i]).hidden = NO;
        }
        if (textField.text.length == kDotCount) {
            NSLog(@"输入完毕");
        }
    }
}

/**
 *  清除密码
 */

- (void)clearUpPassword
{
    textFieldmima.text = @"";
    [self textFieldDidChange:textFieldmima];
}

#pragma mark - - - - - - - - - - Textfield Delegate  - -- - - - - - - -- - - - - -
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    
    return YES;
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    //输入1位，下一步按钮变色
    NSString * textstring = [textField.text stringByReplacingCharactersInRange:range withString:string];
    
    if (textField == textFieldmima){ //输入密码
        if([string isEqualToString:@"\n"]) {
            //按回车关闭键盘
            [textField resignFirstResponder];
            return NO;
        } else if(string.length == 0) {
            //判断是不是删除键
            return YES;
        }
        else if(textstring.length > kDotCount) {
            //输入的字符个数大于6，则无法继续输入，返回NO表示禁止输入
            NSLog(@"输入的字符个数大于6，忽略输入");
            //判断密码是否正确，正确则提示校验成功
            //            [textFieldmima resignFirstResponder];
            return NO;
        } else if(textstring.length == kDotCount){
            nextbtn.userInteractionEnabled = YES;
            nextbtn.backgroundColor = COLORRGBA(59, 214, 117, 1);
            
            return YES;
        }
    }
    return YES;
}
#pragma mark - - - - -- - - - 禁止可被复制粘贴 － － － － －－ － － －
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender
{
    return NO;
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    
    [self.view endEditing:YES];
    return YES;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];

}
#pragma mark - - -- - - - 懒加载 ---- - -- - -

- (AFHTTPSessionManager*)manger{
    
    
    if (!_manger) {
        
        _manger = [AFHTTPSessionManager manager];
        
        _manger.responseSerializer = [AFHTTPResponseSerializer serializer];
        
        _manger.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"application/json", nil];
        
    }
    
    return _manger;
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
